package com.huaqin.customer.expansion;

import java.util.ArrayList;
import java.util.List;

import com.huaqin.customer.SenderInterface;
import com.huaqin.salestracker.SalesTrackerService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

public class SenderReceiver extends BroadcastReceiver{
	
	private static final String TAG = "SenderReceiver";
	private String address =  null;
	private String message =  null;
    private Handler mHandler = null;
	private List<SenderInterface> mSenderList = null;
	private SenderInterface mLastSender = null;

	private Runnable mThread = new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Log.i(TAG, "SendThread Run ==> Search Sender");

            if (mSenderList == null){
                mSenderList = new ArrayList<SenderInterface>();
            }
            
            mSenderList.add(new SMSSender());
            mSenderList.add(new HttpProtocolSender());
            boolean result = false;

            for (int i = 0; i < mSenderList.size(); i++){
                
                SenderInterface sender = mSenderList.get(i);
                if (sender.checkAddress(address)){
                    result = sender.send(address, message);
                    mLastSender = sender;
                    break;
                }

                sender = null;
            }

            if (mLastSender == null || !result){
                Log.e(TAG, "Send Failure mLastSender:" + mLastSender + " result:" + result);
                
                Intent sendIntent = new Intent(SalesTrackerService.STCMD_SEND_RESULT);
                sendIntent.putExtra(SalesTrackerService.KEY_RESULT, false);
                sendIntent.putExtra(SalesTrackerService.KEY_FAILURE, "Send Failure mLastSender:" + mLastSender + " result:" + result);
                SalesTrackerService.mContext.sendBroadcast(sendIntent);
            }
            
            if (mSenderList != null){
                mSenderList = null;
            }
            
            mHandler.removeCallbacks(mThread);
        }
    };

	@Override
    public final void onReceive(final Context context, final Intent intent) {
		// TODO Auto-generated method stub

		if (intent != null){
			
			String action = intent.getAction();
			Log.i(TAG, ">> onReceive action:" + action);
			
			if (SalesTrackerService.STCMD_SEND_ACTION.equals(action)){
				address = intent.getStringExtra(SalesTrackerService.KEY_ADDRESS);
				message = intent.getStringExtra(SalesTrackerService.KEY_MESSAGE);
			}
			
			Log.i(TAG, "Receive address:[" + address + "]\nmessage:[" + message + "]");
			
			if (address == null || message == null){
				return;
			}
			
			if(mHandler == null){
	            mHandler = new Handler();
	        }

	        mHandler.post(mThread);
		}
	}
}
